package com.ruoyi.common.core.page;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.bean.BeanCopier;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.function.Function;

/**
 * 分页响应数据
 *
 * @author tqfeiyang
 * @since 2024/11/28 15:57
 */
@Data
@RequiredArgsConstructor
public class PagingData<T>
{
    @Schema(description = "总记录数")
    private final long total;

    @Schema(description = "总页数")
    private final long pages;

    @Schema(description = "当前页")
    private final long pageNum;

    @Schema(description = "每页的数量")
    private final long pageSize;

    @Schema(description = "结果集")
    private final List<? extends T> list;

    public static <T> PagingData<T> of(List<? extends T> list) {
        PageInfo<? extends T> info = new PageInfo<>(list);
        return new PagingData<T>(
                info.getTotal(),
                info.getPages(),
                info.getPageNum(),
                info.getPageSize(),
                list
        );
    }

    public static <S, R> PagingData<R> of(List<? extends S> list, Class<R> destinationType) {
        return of(list, item -> BeanCopier.copy(item, destinationType));
    }

    public static <S, T> PagingData<T> of(List<? extends S> list, Function<S, ? extends T> mapper)
    {
        PageInfo<? extends S> info = new PageInfo<>(list);
        return new PagingData<T>(
                info.getTotal(),
                info.getPages(),
                info.getPageNum(),
                info.getPageSize(),
                list.stream().map(mapper).toList()
        );
    }
}
